<template>
  <div>
    <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="120px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="dataForm.username" name="username" type="text" auto-complete="on" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="dataForm.password" name="password" auto-complete="on" placeholder="请输入密码" @keyup.enter.native="handleLogin" />
      </el-form-item>
      <el-form-item>
        <el-button :loading="loading" type="primary" @click.native.prevent="handleLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data(){
    return {
      dataForm: {
        username: '', 
        password: ''
      },
      rules: {
        username: [
          { required: true, message: "账户不能为空", trigger: "blur" },
          { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ]
      },
      loading: false,
    }
  },
  methods: {
    handleLogin() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$http({
            url: '/dev-api/login',
            method: 'post',
            data: this.dataForm
          }).then(res => {
            if(res.code == 200){
              this.loading = false
              this.$cookies.set('token', res.token)
              this.$router.push({
                name: 'home'
              })
            }
          })
        } else {
          return false;
        }
      })
    },
  }
}
</script>

<style>

</style>